package com.micro.ai.files.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.files.entity.FileFavorite;
import com.micro.ai.files.mapper.FileFavoriteMapper;
import com.micro.ai.files.service.FileFavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 文件收藏服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class FileFavoriteServiceImpl extends ServiceImpl<FileFavoriteMapper, FileFavorite> implements FileFavoriteService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileFavorite addFavorite(FileFavorite favorite) {
        if (favorite == null) {
            throw new BusinessException("F0000", "收藏信息不能为空");
        }
        
        if (!StringUtils.hasText(favorite.getTenantId())) {
            throw new BusinessException("F0000", "租户ID不能为空");
        }
        
        if (!StringUtils.hasText(favorite.getUserId())) {
            throw new BusinessException("F0000", "用户ID不能为空");
        }
        
        if (!StringUtils.hasText(favorite.getFileId())) {
            throw new BusinessException("F0000", "文件ID不能为空");
        }
        
        // 检查是否已收藏
        if (isFavorited(favorite.getTenantId(), favorite.getUserId(), favorite.getFileId())) {
            throw new BusinessException("F0001", "文件已收藏");
        }
        
        favorite.setCreatedAt(LocalDateTime.now());
        
        boolean success = this.save(favorite);
        if (!success) {
            throw new BusinessException("F0003", "添加收藏失败");
        }
        
        log.info("添加收藏成功: favoriteId={}, userId={}, fileId={}", 
                favorite.getId(), favorite.getUserId(), favorite.getFileId());
        return favorite;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeFavorite(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("F0000", "收藏ID不能为空");
        }
        
        FileFavorite favorite = this.getById(id);
        if (favorite == null) {
            throw new BusinessException("F0002", "收藏记录不存在: " + id);
        }
        
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("F0003", "取消收藏失败");
        }
        
        log.info("取消收藏成功: favoriteId={}, userId={}, fileId={}", 
                id, favorite.getUserId(), favorite.getFileId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeFavoriteByUserAndFile(String tenantId, String userId, String fileId) {
        LambdaQueryWrapper<FileFavorite> query = new LambdaQueryWrapper<>();
        query.eq(FileFavorite::getTenantId, tenantId)
             .eq(FileFavorite::getUserId, userId)
             .eq(FileFavorite::getFileId, fileId);
        
        this.remove(query);
        
        log.info("取消收藏成功: tenantId={}, userId={}, fileId={}", tenantId, userId, fileId);
    }

    @Override
    public boolean isFavorited(String tenantId, String userId, String fileId) {
        LambdaQueryWrapper<FileFavorite> query = new LambdaQueryWrapper<>();
        query.eq(FileFavorite::getTenantId, tenantId)
             .eq(FileFavorite::getUserId, userId)
             .eq(FileFavorite::getFileId, fileId);
        
        return this.count(query) > 0;
    }

    @Override
    public Page<FileFavorite> pageQuery(int pageNum, int pageSize, String tenantId, String userId) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<FileFavorite> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<FileFavorite> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(FileFavorite::getTenantId, tenantId);
        }
        if (StringUtils.hasText(userId)) {
            query.eq(FileFavorite::getUserId, userId);
        }
        
        query.orderByDesc(FileFavorite::getCreatedAt);
        
        return this.page(page, query);
    }

    @Override
    public List<FileFavorite> listByUser(String tenantId, String userId) {
        LambdaQueryWrapper<FileFavorite> query = new LambdaQueryWrapper<>();
        query.eq(FileFavorite::getTenantId, tenantId)
             .eq(FileFavorite::getUserId, userId)
             .orderByDesc(FileFavorite::getCreatedAt);
        
        return this.list(query);
    }
}

